package com.atguigu.tingshu.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //1.先查询本地是否存在交易记录, 有的话直接返回即可
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, orderNo));
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.没有的话,添加交易记录
        paymentInfo = new PaymentInfo();
        //支付类型：1301-订单 1302-充值
        paymentInfo.setPaymentType(paymentType);
        //订单编号
        paymentInfo.setOrderNo(orderNo);
        //交易编号（微信或支付）
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        // 交易状态：1401-未支付 1402-已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);

        //订单支付类型为订单时
        if (paymentType.equals(SystemConstant.PAYMENT_TYPE_ORDER)) {
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();

            String orderStatus = orderInfo.getOrderStatus();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)) {
                throw new RuntimeException("订单状态有误");
            }
            paymentInfo.setUserId(orderInfo.getUserId());
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }
        //订单支付类型为充值时
        if (paymentType.equals(SystemConstant.PAYMENT_TYPE_RECHARGE)) {
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            String rechargeStatus = rechargeInfo.getRechargeStatus();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeStatus)) {
                throw new RuntimeException("充值状态有误");
            }
            paymentInfo.setUserId(rechargeInfo.getUserId());
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            paymentInfo.setContent("充值：" + rechargeInfo.getRechargeAmount());
        }




        /*paymentInfo.setOutTradeNo();
        paymentInfo.setCallbackTime();
        paymentInfo.setCallbackContent();*/

        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }

    /**
     * 更新交易记录
     *
     * @param transaction: 微信返回的交易记录
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void updatePaymentInfo(Transaction transaction) {
        String outTradeNo = transaction.getOutTradeNo();
        //根据订单编号查询交易记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderNo, outTradeNo));
        String paymentStatus = paymentInfo.getPaymentStatus();
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentStatus)) {
            throw new RuntimeException("该订单已支付");
        }
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        baseMapper.updateById(paymentInfo);

        //支付类型:1301-订单 1302-充值
        String paymentType = paymentInfo.getPaymentType();
        //如果支付类型是下订单:
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //更新订单支付信息
            Result result = orderFeignClient.orderPaySuccess(outTradeNo);
            if (result.getCode().intValue() != 200) {
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }

        //如果支付类型为充值
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //更新充值信息
            Result result = accountFeignClient.rechargePaySuccess(outTradeNo);
            if (result.getCode().intValue() != 200) {
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }
    }
}
